import Vue from 'vue'
import VueRouter from 'vue-router'

import routes from '@/route/routes'
import store from '@/store'

// import { reqGetUserInfo } from '@/api'

Vue.use(VueRouter);

const oldPush = VueRouter.prototype.push

VueRouter.prototype.push = function (location, resolve = () => { }, reject = () => { }) {

    oldPush.call(this, location, resolve, reject)
}

const router = new VueRouter({
    mode: 'history',
    routes: routes,
    scrollBehavior() {
        return { x: 0, y: 0 }
    }
})


// 定义路由守卫白名单
const whitePath = ['login', 'register', 'detail', 'search', 'home', 'addcartsuccess']

// 全局路由守卫
router.beforeEach(async (to, from, next) => {
    // 获取token
    const token = store.state.user.token;


    // 判断是否有token
    if (token) {
        if (to.name === 'login') {
            next('/home')
        } else {
            // 如果有token 判断是否有用户信息，有直接放行，没有则先获取用户信息后再放行
            // 获取用户信息
            const isUserInfo = store.state.user.userInfo.id
            if (isUserInfo) {
                next();
            } else {
                try {
                    await store.dispatch('user/getUserInfo');
                    next();
                } catch (e) {
                    store.commit('user/logOut')
                    next('/login')
                    alert(e.message + '或者登录已过期')
                }
            }

        }

    } else {
        // 没有token 的时候,判断去的路由是否在白名单中
        if (whitePath.includes(to.name)) {
            // 如果在白名单中则放行
            next();
        } else {
            // 不在白名单中就跳转到登录页登录
            next('/login')
        }
    }
})

export default router